package cn.iphone.NPlayer.service.impl;

import cn.iphone.NPlayer.constants.RedisSmsConstants;
import cn.iphone.NPlayer.domain.MessageBlacklist;
import cn.iphone.NPlayer.exception.GlobalExceptionCodeEnum;
import cn.iphone.NPlayer.mapper.MessageBlacklistMapper;
import cn.iphone.NPlayer.service.IMessageBlacklistService;
import cn.iphone.NPlayer.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ikun
 * @since 2022-11-25
 */
@Service
public class MessageBlacklistServiceImpl extends ServiceImpl<MessageBlacklistMapper, MessageBlacklist> implements IMessageBlacklistService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public boolean insert(MessageBlacklist messageBlacklist) {
        // 判断黑名单中是否有该手机号
        Wrapper<MessageBlacklist> wrapper = new EntityWrapper<>();
        wrapper.eq("phone",messageBlacklist.getPhone());
        MessageBlacklist black = selectOne(wrapper);
        // 如果为null 就添加到黑名单
        AssertUtil.isNull(black, GlobalExceptionCodeEnum.BLACK_ERROR);
        messageBlacklist.setCurrentTime(new Date());
        insert(messageBlacklist);

        // 将黑名单添加到redis
        List<MessageBlacklist> messageBlacks = selectList(null);
        // 拼接业务键
        String rediskey = String.format(RedisSmsConstants.REDIS_REGISTER_BLACK_KEY, messageBlacks);
        redisTemplate.opsForValue().set(rediskey, JSON.toJSONString(messageBlacks));
        return super.insert(messageBlacklist);

    }

    @Override
    public boolean deleteById(Serializable id) {
        // 清除缓存
        List<MessageBlacklist> messageBlacks = selectList(null);
        String rediskey = String.format(RedisSmsConstants.REDIS_REGISTER_BLACK_KEY, messageBlacks);
        redisTemplate.delete(rediskey);

        // 删除黑名单
        Wrapper<MessageBlacklist> wrapper = new EntityWrapper<>();
        wrapper.eq("id",id);
        delete(wrapper);
        return super.deleteById(id);
    }
}
